import React, { Component } from "react";
import { connect } from "react-redux";
import { Modal, Form, Input, Select, message, Spin } from "antd";
import { openModal, removeContainer } from "components/method/openModal";
import { messages } from "share/common";
import PDService from "../../containers/enterprise-manage/person-manage/person-detail/person-detail.service";
import Chooser from "components/chooser";

const { Item } = Form;
const { Option } = Select;

@Form.create()
@connect(mapStateToProps)
class PersonAccount extends Component {
  state = {
    confirmLoading: false,
    cardTypeList: [],
    loading: false,
  };

  componentDidMount() {
    this.setState({ loading: true });
    PDService.getCardTypes()
      .then((res) => {
        this.setState({ loading: false, cardTypeList: res.data.values });
      })
      .catch((e) => {
        message.error(e.response.data.message);
        this.setState({ loading: false });
      });
  }

  handleOk = () => {
    const { onOk } = this.props;
    this.props.form.validateFieldsAndScroll((err, value) => {
      if (!err) {
        let e = value.bank;
        delete value.bank;
        value = Object.assign(value, {
          bankCode: e[0].bankCode,
          branchName: e[0].bankBranchName,
          bankName: e[0].bankName,
          bankType: e[0].bankType,
          bankTypeBankCode: e[0].bankType + e[0].bankCode,
          enable: true,
          isPrimary: false,
        });
        this.setState({ confirmLoading: true });
        PDService.creatBankCard(value)
          .then((res) => {
            this.setState({ confirmLoading: false });
            onOk(res.data);
          })
          .catch(() => {
            this.setState({ confirmLoading: false });
          });
      }
    });
  };

  handleBankCodeChange = (value) => {
    value &&
      value[0] &&
      this.props.form.setFieldsValue({
        accountLocation: value[0].openAccount,
      });
  };

  render() {
    const { onCancel, visible, user, loginUser, company } = this.props;
    const { confirmLoading, loading, cardTypeList } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    };
    let nowUser = user || loginUser;
    return (
      <Modal
        visible={visible}
        onCancel={onCancel}
        onOk={this.handleOk}
        title={messages("common-1.key1379") /*添加员工银行账号*/}
        confirmLoading={confirmLoading}
      >
        <Form>
          <h3 className="sub-title">{messages("common-1.key570") /*员工信息*/}</h3>
          <Item label={messages("common.user.id") /*工号*/} {...formItemLayout} required>
            <Input value={nowUser.employeeID} disabled />
          </Item>
          <Item label={messages("common-1.key500") /*姓名*/} {...formItemLayout} required>
            <Input value={nowUser.fullName} disabled />
          </Item>
          <h3 className="sub-title">{messages("common-1.key1380") /*员工银行账号信息*/}</h3>
          <Item {...formItemLayout} label={messages("basic-5.key394") /*银行卡类型*/}>
            {getFieldDecorator("bankAccountType", {
              rules: [
                {
                  required: true,
                  message: messages("basic-5.key2") /*请选择*/,
                },
              ],
            })(
              <Select
                placeholder={messages("basic-5.key2") /*请选择*/}
                allowClear
                notFoundContent={loading ? <Spin size="small" /> : messages("common.unmatched") /*无匹配结果*/}
              >
                {cardTypeList.map((option) => (
                  <Option key={option.value}>{option.messageKey}</Option>
                ))}
              </Select>
            )}
          </Item>
          <Item label={messages("basic-5.key152") /*银行名称*/} {...formItemLayout}>
            {getFieldDecorator("bank", {
              rules: [
                {
                  required: true,
                  message: messages("common.please.input") /*请输入*/,
                },
              ],
            })(
              <Chooser
                single
                type="select_bank"
                locale={{
                  emptyText: messages(
                    "finance-4.key426"
                  ) /*当前条件没有搜索到银行，建议分词以提高搜索命中率，例：【工商银行深圳华侨城支行】改为【工商银行 深圳 华侨城支行】*/,
                }}
                onChange={this.handleBankCodeChange}
                placeholder={messages("common.select") /*请选择*/}
                labelKey="bankBranchName"
                valueKey="bankCode"
              />
            )}
          </Item>
          <Item {...formItemLayout} label={messages("basic-5.key395") /*银行开户名*/}>
            {getFieldDecorator("bankAccountName", {
              rules: [
                {
                  required: true,
                  message: messages("common.please.input") /*请输入*/,
                },
                {
                  max: 100,
                  message: messages("basic-5.key396") /*不能超过100个字符*/,
                },
              ],
              initialValue: company.employeeNameReal ? nowUser.fullName : undefined,
            })(
              <Input
                placeholder={messages("finance-4.key70") /*请输入*/}
                disabled={company.employeeNameReal && company.nameFollowType === "followedAndUnmodified"}
              />
            )}
          </Item>
          <Item {...formItemLayout} label={messages("basic-5.key208") /*银行卡号*/}>
            {getFieldDecorator("bankAccountNo", {
              rules: [
                {
                  required: true,
                  message: messages("common.please.input") /*请输入*/,
                },
                {
                  message: messages("basic-5.key398") /*必须包含数字*/,
                  validator: (rule, value, cb) => {
                    let regExp = /[0-9]/;
                    //去掉空格
                    value = (value || "").replace(/ /g, "");
                    if (regExp.test(value)) {
                      cb();
                    } else {
                      cb(false);
                    }
                  },
                },
                {
                  max: 30,
                  message: messages("basic-5.key249") /*不能超过30个字符*/,
                },
              ],
            })(<Input placeholder={messages("finance-4.key70") /*请输入*/} />)}
          </Item>
          <Item {...formItemLayout} label={messages("basic-5.key155") /*开户地*/}>
            {getFieldDecorator("accountLocation", {
              rules: [
                {
                  required: true,
                  message: messages("common.please.input") /*请输入*/,
                },
                {
                  max: 100,
                  message: messages("basic-5.key396") /*不能超过100个字符*/,
                },
              ],
            })(<Input placeholder={messages("finance-4.key70") /*请输入*/} />)}
          </Item>
        </Form>
      </Modal>
    );
  }
}

PersonAccount.open = function (env, params) {
  let container;
  return new Promise((resolve) => {
    const targetProps = {
      visible: true,
      onOk: (data) => close(data),
      onCancel: () => close(null),
      afterClose: () => {
        removeContainer(container);
        container = null;
      },
      ...(params || {}),
    };
    function close(data) {
      let closeModal = () =>
        openModal(
          PersonAccount,
          {
            ...targetProps,
            visible: false,
          },
          env,
          container
        );
      if (data !== null) {
        closeModal();
        resolve(data);
      } else closeModal();
    }
    container = openModal(PersonAccount, targetProps, env);
  });
};

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser,
    company: state.login.company,
  };
}

export default PersonAccount;
